#include <tinyalsa/asoundlib.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <endian.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>   // tolower()

#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT  0x20746d66
#define ID_DATA 0x61746164

typedef enum {false = 0, true = 1} bool;


struct riff_wave_header {
    uint32_t riff_id;
    uint32_t riff_sz;
    uint32_t wave_id;
};

struct chunk_header {
    uint32_t id;
    uint32_t sz;
};

struct chunk_fmt {
    uint16_t audio_format;
    uint16_t num_channels;
    uint32_t sample_rate;
    uint32_t byte_rate;
    uint16_t block_align;
    uint16_t bits_per_sample;
};

#undef TAG
#define TAG "BPLAY"
#if 0      // def 0__ANDROID__
#include <android/log.h>
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#else
#define LOGI(str, ...) do{printf("BPLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGD(str, ...) do{printf("BPLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGW(str, ...) do{printf("BPLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGE(str, ...) do{printf("BPLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#endif


static int isClosing = 0;
int g_pausing = 0;
int32_t g_seek_seconds = 0;

void play_sample(FILE *file, unsigned int card, unsigned int device,
                 unsigned int src_channels, unsigned int dest_channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count, uint32_t data_sz);

void stream_close(int sig) {
    /* allow the stream to be closed gracefully */
    signal(sig, SIG_IGN);
    isClosing = 1;
}

void* play_thread(void* arg) {
    FILE *file = NULL;
    struct chunk_header chunk_header;
    struct riff_wave_header riff_wave_header;
    struct chunk_fmt chunk_fmt;
    unsigned int device = 0;
    unsigned int card = 0;
    unsigned int period_size = 1024;
    unsigned int period_count = 4;
    unsigned int dest_channels = 0;
    const char *filename;
    int more_chunks = 1;
    char ** argv = (char **) arg;

    filename = argv[1];
    file = fopen(filename, "rb");
    if (!file) {
        LOGE("Unable to open file '%s'\n", filename);
        return (void*)(long)1;
    }

    fread(&riff_wave_header, sizeof(riff_wave_header), 1, file);
    if ((riff_wave_header.riff_id != ID_RIFF) ||
        (riff_wave_header.wave_id != ID_WAVE)) {
        LOGI("Error: '%s' is not a riff/wave file\n", filename);
        fclose(file);
        return (void*)(long)1;
    }
    do {
        fread(&chunk_header, sizeof(chunk_header), 1, file);

        switch (chunk_header.id) {
        case ID_FMT:
            fread(&chunk_fmt, sizeof(chunk_fmt), 1, file);
            /* If the format header is larger, skip the rest */
            if (chunk_header.sz > sizeof(chunk_fmt))
                fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR);
            break;
        case ID_DATA:
            /* Stop looking for chunks */
            more_chunks = 0;
            chunk_header.sz = le32toh(chunk_header.sz);
            break;
        default:
            /* Unknown chunk, skip bytes */
            fseek(file, chunk_header.sz, SEEK_CUR);
        }
    } while (more_chunks);

    /* parse command line arguments */
    argv += 2;
    while (*argv) {
        if (strcmp(*argv, "-c") == 0) {
            argv++;
            if (*argv)
                dest_channels = atoi(*argv);
        }
        if (strcmp(*argv, "-d") == 0) {
            argv++;
            if (*argv)
                device = atoi(*argv);
        }
        if (strcmp(*argv, "-p") == 0) {
            argv++;
            if (*argv)
                period_size = atoi(*argv);
        }
        if (strcmp(*argv, "-n") == 0) {
            argv++;
            if (*argv)
                period_count = atoi(*argv);
        }
        if (strcmp(*argv, "-D") == 0) {
            argv++;
            if (*argv)
                card = atoi(*argv);
        }
        if (*argv)
            argv++;
    }

    play_sample(file, card, device, chunk_fmt.num_channels, dest_channels, chunk_fmt.sample_rate,
                chunk_fmt.bits_per_sample, period_size, period_count, chunk_header.sz);

    fclose(file);

    return (void*)(long)0;
}

void displayHelp() {
    LOGI("Valid commands:");
    LOGI("h - help");
    LOGI("q - quit process");
    LOGI("p - pause playing");
    LOGI("r - resume playing");
    LOGI("s - seek to ");
    LOGI("----------------------");
}

void performActionResume() {
    g_pausing = 0;
    LOGI("resuming...");
}

void performActionPause() {
    g_pausing = 1;
    LOGI("pausing...");
}

void performActionWait() {
    g_pausing = 2;
    LOGI("Waiting...");
}

void performActionSeekTo(int sec) {
    LOGI("Seek to %d sec", sec);
    if (sec > 0) {
        g_seek_seconds = sec;
    }
}

int main(int argc, char* argv[]) {
    pthread_t tid;
    void* status;

    if (argc < 2) {
        LOGI("Usage: %s file.wav [-D card] [-d device] [-p period_size]"
                " [-n n_periods] \n", argv[0]);
        return 1;
    }

     if (pthread_create(&tid, NULL, play_thread, (void*)argv)) {
         return 1;
    }

    char command[5];
    while(1) {
        memset(command, 0, 5);
        scanf(" %4s", command);
        command[0] = tolower(command[0]);

        switch(command[0]) {
            case 'h':
                displayHelp();
                break;
            case 'q':
                exit(0);
            case 'r':
                performActionResume();
                break;
            case 'p':
                performActionPause();
                break;
            case 's': {
                int seek_second = atoi(&command[1]);
                performActionSeekTo(seek_second);
                }
                break;
            case 'w': {
                performActionWait();
            }
        }
    }

    return 0;
}

int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
                 char *param_name, char *param_unit) {
    unsigned int min;
    unsigned int max;
    int is_within_bounds = 1;

    min = pcm_params_get_min(params, param);
    if (value < min) {
        LOGW("%s is %u%s, device supports >= %u%s\n", param_name, value, param_unit, min, param_unit);
        //is_within_bounds = 0;
    }

    max = pcm_params_get_max(params, param);
    if (value > max) {
        LOGE("%s is %u%s, device only supports <= %u%s\n", param_name, value,
                param_unit, max, param_unit);
        is_within_bounds = 0;
    }

    return is_within_bounds;
}

int sample_is_playable(unsigned int card, unsigned int device, unsigned int channels,
                        unsigned int rate, unsigned int bits, unsigned int period_size,
                        unsigned int period_count) {
    struct pcm_params *params;
    int can_play;

    params = pcm_params_get(card, device, PCM_OUT);
    if (params == NULL) {
        LOGE("Unable to open PCM device %u.\n", device);
        return 0;
    }

    can_play = check_param(params, PCM_PARAM_RATE, rate, "Sample rate", "Hz");
    can_play &= check_param(params, PCM_PARAM_CHANNELS, channels, "Sample", " channels");
    can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, bits, "Bitrate", " bits");
    can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, period_size, "Period size", " frames");
    can_play &= check_param(params, PCM_PARAM_PERIODS, period_count, "Period count", " periods");

    pcm_params_free(params);

    return can_play;
}

static int merge_data_to_channel(char* out_buffer, const char* in_buffer, int src_size,
                                   int src_channels, int dest_channels, int bit_width) {
    int i = 0;
    int copy_channels = src_channels;
    if (src_channels > dest_channels) copy_channels = dest_channels;
    int loop_count = src_size / bit_width / src_channels;

    for(; i < loop_count; i ++) {
        memcpy(out_buffer + i * dest_channels * bit_width,
               in_buffer + i * bit_width * src_channels,
               bit_width * copy_channels);
    }
    return src_size * dest_channels / src_channels;
}

void play_sample(FILE *file, unsigned int card, unsigned int device,
                 const unsigned int src_channels, const unsigned int dest_channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count, const uint32_t full_data_size) {
    struct pcm_config config;
    struct pcm *pcm = NULL;
    char *write_buffer = NULL;
    char *read_buffer = NULL;
    unsigned int write_buffer_size = 0, read_buffer_size = 0, read_sz;
    int num_read;
    uint32_t frame_count = 0;
    uint32_t loop_times = 0;
    uint32_t byte_rate = 1;
    uint32_t total_seconds = 0;
    uint32_t current_seconds = 0;
    uint32_t min_channel = 1, max_channels = 1;
    struct pcm_params *params;
    uint32_t data_sz = full_data_size;
    bool called_pause = false;

    int bit_width = 1;
    bit_width = bits / 8;

     memset(&config, 0, sizeof(config));

    params = pcm_params_get(card, device, PCM_OUT);
    min_channel = pcm_params_get_min(params, PCM_PARAM_CHANNELS);
    max_channels = pcm_params_get_max(params, PCM_PARAM_CHANNELS);

   if (src_channels < min_channel) {
        LOGW("convert config.channels to %d instead of %d", min_channel, src_channels);
        config.channels = min_channel;
    } else if (src_channels > max_channels) {
        LOGW("convert config.channels to %d instead of %d", max_channels, src_channels);
        config.channels = max_channels; 
    } else if(dest_channels > 0){
        config.channels = dest_channels;
    } else {
        config.channels = src_channels;
    }


    config.rate = rate;
    config.period_size = period_size;
    config.period_count = period_count;
    if (bits == 32)
        config.format = PCM_FORMAT_S32_LE;
    else if (bits == 24)
        config.format = PCM_FORMAT_S24_3LE;
    else if (bits == 16)
        config.format = PCM_FORMAT_S16_LE;
    config.start_threshold = 0;
    config.stop_threshold = 0;
    config.silence_threshold = 0;

    do {
        if (!sample_is_playable(card, device, config.channels, rate, bits, period_size, period_count)) {
            LOGE("sample is not playable");
            break;
        }

        pcm = pcm_open(card, device, PCM_OUT, &config);
        if (!pcm || !pcm_is_ready(pcm)) {
            LOGE("Unable to open PCM device %u (%s)\n",
                    device, pcm_get_error(pcm));
            break;
        }

        write_buffer_size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
        write_buffer = (char*)malloc(write_buffer_size);
        memset(write_buffer, 0, write_buffer_size);
        read_buffer_size = write_buffer_size * src_channels / config.channels;
        read_buffer = (char*)malloc(write_buffer_size * src_channels / config.channels);

        if (!write_buffer || !read_buffer) {
            LOGE("Unable to allocate %d bytes\n", read_buffer_size + write_buffer_size);
            free(write_buffer);
            free(read_buffer);
            pcm_close(pcm);
            break;
        }
    } while(0);

    byte_rate = (uint32_t) ((src_channels * rate * bits) / 8);
    total_seconds = (uint32_t)(data_sz / byte_rate);

    LOGD(">>> %u ch, %u hz, %u bit byte_rate=%u. Total %u bytes, %u seconds.",
                       config.channels, rate, bits, byte_rate, data_sz, total_seconds);

    LOGD(">>> pcm_get_buffer_size(): %d, write_size: %d, read size:%d",
                       pcm_get_buffer_size(pcm), write_buffer_size, read_buffer_size);

    /* catch ctrl-c to shutdown cleanly */
    signal(SIGINT, stream_close);

    do {
        uint32_t t = total_seconds - data_sz / byte_rate;
        if ((t - current_seconds) >= 1) {
            current_seconds = t;
            printf("\rPlayed %d seconds, [%d]bytes remain.", current_seconds, data_sz);
            fflush(stdout);
        }

        if(g_seek_seconds != 0) {
            if(total_seconds > (current_seconds + g_seek_seconds) && (current_seconds + g_seek_seconds) > 0 ) {
                int32_t seek_bytes = byte_rate * g_seek_seconds;
                seek_bytes -= seek_bytes % write_buffer_size;
                LOGD("Seek to second: %d, seek bytes=%d",g_seek_seconds, seek_bytes);
                fseek(file, seek_bytes, SEEK_CUR);
                data_sz = full_data_size - seek_bytes;
            }
            g_seek_seconds = 0;
        }

        if(g_pausing > 0) {
            if(!called_pause) {
                called_pause = true;
                if (g_pausing == 2) pcm_wait(pcm, -1);
            }
            usleep(100*1024);
            continue;
        }
        called_pause = false;

        memset(read_buffer, 0, read_buffer_size);
        memset(write_buffer, 0, write_buffer_size);
        read_sz = read_buffer_size < data_sz ? read_buffer_size : data_sz;
        num_read = fread(read_buffer, 1, read_sz, file);
        if (num_read > 0) {
            merge_data_to_channel(write_buffer, read_buffer, read_sz, src_channels, config.channels, bit_width);
            if (pcm_write(pcm, write_buffer, write_buffer_size)) {
                LOGE("Error playing sample, remain bytes=%d, loop=%d", data_sz, loop_times);
                // receiving signal may interrupt some system call.
            }
            frame_count++;
            data_sz -= num_read;
        }
    } while (!isClosing && num_read > 0 && data_sz > 0);
    printf("\nEnd playing.\n");
    fflush(stdout);
    free(write_buffer);
    free(read_buffer);
    if(NULL != pcm)pcm_close(pcm);
    exit(0);
}